#!/usr/bin/env perl

BEGIN {
	push @::INC,".." if -f "../pv3.pm";
	push @::INC,$::ENV{CODEMGR_LIBS} if exists($::ENV{CODEMGR_LIBS});
}

use pv3;
use Getopt::Long;
use Data::Dumper;
use POSIX qw(strftime);
use strict;
use Config;

$::ARG_pv=undef;
$::ARG_version=undef;
$::ARG_context=0;
$::ARG_old=0;
$::ARG_unified=0;

sub usage {
	print "
Usage: pv3_diff [-c|-o|-u] [-p DIR] [-v v1[,v2]] file ...

The pv3_diff commands should information about
a particular file (or version) that is under PV3 code
control.

It supports the following command line arguments:

-p  By default the file in question containing the versions is
    thought to exist in the current directory. Use this option
    to reference the version file kept elsewhere.
-v  Two versions to show the differences between, comma 
    separated. If only one version is given then the difference
    will be between that version and the latest version, unless
    the file is currently checked out. If it is checked out it will
    be between the version specified and the current file contents.
-c  Context style of diff output, easiest to read.
-o  Original style of diff output, not often used.
-u  Unified style of diff output, suitable for the patch(1) command.
 
Please note that if no -v option is specified then the contents
of the current file will be compared to the contents of the most
recently checked in version.

If no files are given it will provide all information for all
files currently under code control in the specified code repository.

Written by Simon Edwards, (C) 2006-2010 www.advantsys.co.uk
";
	exit 1;
}

if(!GetOptions(
	"context"	=> \$::ARG_context,
	"old"		=> \$::ARG_old,
	"unified"	=> \$::ARG_unified,
	"pv=s"		=> \$::ARG_pv,
	"version=s"	=> \$::ARG_version,
	)) {
	usage;
}

if($::ARG_context+$::ARG_old+$::ARG_unified == 0) {
	$::ARG_unified=1;
}
if($::ARG_context+$::ARG_old+$::ARG_unified != 1) {
	usage;
}

%::args=();
@::VERS=();

if(defined($::ARG_version)) {
	@::VERS=split(/,/,$::ARG_version);
	if(@::VERS>2) {
		usage;
	}
	if(@::VERS==1) {
		push @::VERS,'_CURRENT_';
	}
} else {
	@::VERS=('%HEAD','_CURRENT_');
}

$::args{VERSION1}=$::VERS[0];
$::args{VERSION2}=$::VERS[1];
if($::ARG_context) {
	$::args{STYLE}="context";
}
if($::ARG_unified) {
	$::args{STYLE}="unified";
}
if($::ARG_old) {
	$::args{STYLE}="oldstyle";
}

if($Config{osname} =~ /mswin/i) {
	my @F=();
	for my $cpat (@::ARGV) {
		push @F,glob($cpat);
	}
	@::ARGV=@F;
}

{
	my $ref=pv3::diff(FILE => [@::ARGV],%::args);
	my $oks=0;
	my $fails=0;
	for my $cref (@$ref) {
		if($cref->[0] < 1) {
			print "Error: $cref->[1]\n";
		} else {
			print "$cref->[2]:\n";
			print "${$cref->[1]}\n";
		}
	}
}

exit(0);
